# coding:utf-8
'''
Created on 2011-3-9

@author: Administrator
'''

import re

#=================================
# 在字符串结尾的匹配，将ROAD替换为RD.
#=================================
s = '100 NORTH BROAD ROAD'
print s.replace('ROAD', 'RD.') # 使用最简单的字符串替换，容易错误替换
s = '100 NORTH BROAD ROAD'
print s[:-4] + s[-4:].replace('ROAD', 'RD.') # 使用字符串截取，对字符串格式有要求
s = '100 NORTH BROAD ROAD'
# re.sub函数，对字符串s进行搜索，满足正则表达式“ROAD$”的用“RD.”替换
print re.sub('ROAD$', 'RD.', s) # 使用正则表达式替换

#=================================
# 匹配整个单词，将ROAD替换为RD.
#=================================
s = '100 BROAD'
print re.sub('ROAD$', 'RD.', s)
s = '100 BROAD'
print re.sub('\\bROAD$', 'RD.', s) # \b表示单词的边界
s = '100 BROAD'
print re.sub(r'\bROAD$', 'RD.', s) # r表示正则表达式中的所有字符都不进行转义（即省略了\转义符）
s = '100 BROAD ROAD APT. 3'
print re.sub(r'\bROAD$', 'RD.', s)
s = '100 BROAD ROAD APT. 3'
print re.sub(r'\bROAD\b', 'RD.', s)
